//$Id: RegisterAction.java,v 1.20 2007/02/25 19:09:39 gavin Exp $
package pl.edu.agh.iosr.gamblingzone.action;
import static org.jboss.seam.ScopeType.EVENT;
import java.util.List;
import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.jboss.seam.annotations.Destroy;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.faces.FacesMessages;
import pl.edu.agh.iosr.gamblingzone.model.User;
import pl.edu.agh.iosr.gamblingzone.dao.ejb.UserDAOBean;
import pl.edu.agh.iosr.gamblingzone.dao.UserDAO;
import java.util.Date;

@Stateful
@Scope(EVENT)
@Name("register")
public class MyRegisterAction implements MyRegister
{
   @In
   private User user;
   
   @PersistenceContext
   private EntityManager em;
   
   @In
   private FacesMessages facesMessages;
   
   private String verify;
   
   private boolean registered;
   
   public void register()
   {
	if ( user.getPassword().equals(verify) )
      	{
		UserDAOBean userDAO = new UserDAOBean();
		userDAO.setEntityManager(em);

		// Authenticate user via DAO	
		if(userDAO.authenticateUser(user.getLoginName(), user.getPassword())) {
			facesMessages.addToControl("username", "Username #{user.username} already exists");
		} else {
			user.setRole("aaa");
			user.setBirthDate(new Date());
			
			em.persist(user);
            		facesMessages.add("Successfully registered as #{user.loginName}");
            		registered = true;
		}
	}
	else 
	{
		facesMessages.addToControl("verify", "Re-enter your password");
		verify=null;
	}
   }
   
   public void invalid()
   {
      facesMessages.add("Please try again");
   }
   
   public boolean isRegistered()
   {
      return registered;
   }
   public String getVerify()
   {
      return verify;
   }
   public void setVerify(String verify)
   {
      this.verify = verify;
   }
   
   @Destroy @Remove
   public void destroy() {}
}
